from typing import Mapping
import requests
import json


def get_token():
    client_id = 'os.client.000027'
    uid = 797458
    device_id = 'test'

    post_data = {'osClientId': client_id, 'deviceId': device_id, 'uid': uid, 'osRefreshToken': ''}

    rsp = requests.post('http://api.ximalaya.com/xy-os-console/xy-os-ucenter/test/token', post_data)

    token = json.loads(rsp.text.strip()).get('osAccessToken')
    return token


def handle_query_to_pcm(query):
    token = get_token()

    params = "{'osClientId':'os.client.000027','osAccessToken':'" + token + "','deviceType':2,'deviceId':'test','sysType':1,'appVersion':'1.0','sysVersion':'1.0','speakerVersion':'1.0','romVersion':'1.0','dt':1555131463238,'productId':'N_PROD1_7','sn':'YAMI00018A9000D8'}"
    session = {"attributes": {"a": "b"}, "sid": "857a0ce6e5dd507b958f12995eb514e4"}
    sig = 'd113137e3e36cc5e688f0caf8c2efc66'
    volume = 10
    url = "%s?session=%s&params=%s&sig=%s&aotuman=true&text=%s&volume=%s" % (
    'http://api.ximalaya.com/smart-os-gateway/smart-os-openapi/voice/text2audio', session, params, sig, query, volume)
    # print(url)
    rsp = requests.get(url)
    mp3_file = rsp.content
    # print(mp3_file)

    save_file = query + '.' + 'mp3'
    pcm_file = query + '.' + 'pcm'
    # print(scriptName)
    # mp3_path = '/Users/xmly/Desktop/mp3/' + save_file
    mp3_path = './' + save_file
    # pcm_path = __file__.replace(scriptName, './pcm/' + pcm_file)
    with open(mp3_path, 'wb') as of:
        of.write(mp3_file)
    # cmd = "ffmpeg -i %s -acodec pcm_s16le -f s16le %s >/dev/null 2>&1" % (mp3_path, pcm_path)
    # os.system(cmd)
    return mp3_path


if __name__ == '__main__':
    handle_query_to_pcm('播放刘德华的忘情水')
